<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <img src="/src/static/登录logo.png-removebg-preview.png" alt="">
          <p class="subtitle">安全登录，开启您的二手交易之旅</p>
        </div>
      </template>
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="loginForm"
        label-width="100px"
        class="login-form"
      >
        <el-form-item prop="username" label-width="100px">
          <el-input
            v-model="ruleForm.username"
            type="text"
            placeholder="请输入用户名/学号"
            prefix-icon="User"
            clearable
            @keyup.enter="Login"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="ruleForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
            @keyup.enter="Login"
          />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-radio-group v-model="ruleForm.role">
            <el-radio value="admin">管理员</el-radio>
            <el-radio value="user">用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            @click="Login" 
            :loading="loading"
            class="login-btn"
          >
            登录
          </el-button>
        </el-form-item>
        <div class="footer-links">
          <el-link type="primary" @click="goRegister">注册账号</el-link>
          <el-divider direction="vertical" />
          <el-link type="info" @click="forgetPassword">忘记密码?</el-link>
        </div>
      </el-form>
    </el-card>
    <div class="copyright">
      ©2025 校园二手交易平台 - 让闲置物品流动起来
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

const router = useRouter();
const loginForm = ref(null);
const loading = ref(false);

const ruleForm = ref({
  username: '',
  password: '',
  role: 'user'
});

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
};

const Login = () => {
  loginForm.value.validate((valid) => {
    if (!valid) return;
    
    loading.value = true;
    
    fetch(`http://localhost:3000/users?username=${ruleForm.value.username}`)
      .then(response => response.json())
      .then(data => {
        if (data.length === 0) throw new Error('用户名不存在');
        
        const user = data[0];
        if (user.password !== ruleForm.value.password) throw new Error('密码错误');
        if (user.role !== ruleForm.value.role) throw new Error(`角色不匹配`);
        
        // 存储用户信息
        localStorage.setItem('token', 'Bearer ' + Math.random().toString(36).substr(2));
        localStorage.setItem('user', JSON.stringify(user));
        
        ElMessage.success('登录成功');
        
        // 修正后的跳转逻辑
        const redirectPath = user.role === 'admin' 
          ? '/admin/dashboard' 
          : '/';
          
        router.replace(redirectPath).catch(err => {
          console.error('路由跳转失败:', err);
          router.replace('/index'); // 失败时跳转到首页
        });
      })
      .catch(error => {
        ElMessage.error(error.message || '登录失败');
      })
      .finally(() => {
        loading.value = false;
      });
  });
};

const goRegister = () => {
  try {
    router.push('/register');
  } catch (error) {
    console.error('跳转注册页面时出错:', error);
    ElMessage.error('跳转注册页面失败');
  }
};

const forgetPassword = () => {
  ElMessage.info('重置密码');
};
</script>

<style scoped>
.login-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  /* 移除渐变遮罩，只保留背景图片 */
  background: url('/src/static/背景图.jpg') no-repeat center center;
  background-size: cover;
  padding: 20px;
}

.login-card {
  width: 100%;
  max-width: 420px;
  border-radius: 12px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.1);
  border: none;
  /* 添加背景透明度 */
  background-color: rgba(255, 255, 255, 0.85); /* 85% 不透明度 */
  backdrop-filter: blur(5px); /* 毛玻璃效果 */
}

.card-header {
  text-align: center;
  padding: 10px 0;
}

.card-header h2 {
  margin: 0;
  color: #409EFF;
  font-size: 24px;
}

.subtitle {
  margin: 5px 0 0;
  color: #909399;
  font-size: 14px;
}

.login-form {
  padding: 20px 30px;
}

.el-form-item {
  margin-bottom: 22px;
}

.login-btn {
  width: 100%;
  height: 42px;
  font-size: 16px;
  letter-spacing: 2px;
}

.footer-links {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
}

.copyright {
  margin-top: 30px;
  color: #909399;
  font-size: 12px;
  text-align: center;
}

/* 响应式调整 */
@media (max-width: 480px) {
.login-card {
    margin-top: 0;
    box-shadow: none;
  }
  
.login-form {
    padding: 20px 15px;
  }
}
</style>